﻿<?php

class CommonAdmin
{
    const PRODUCT_ID_MONTH = "Premium_monthly";
    const PRODUCT_ID_YEAR = "Premium_yearly";
    
    const TOTAL_FOR_FREE = 300;//M
    const TOTAL_FOR_PAY = 1024;//M
    
    const COUNT_FOR_FREE = 100;
    const COUNT_FOR_PAY = 1000;
    
    const APPLE_AUTH_URL = 'https://buy.itunes.apple.com/verifyReceipt';//"https://sandbox.itunes.apple.com/verifyReceipt";
    
    public static function ProcessJsonBRError($str)
    {
        if(!empty($str))
        {        
            $order = array("\r\n", "\n", "\r");
            
            $str = str_replace($order," ",$str);
        }
        
        return $str;
    }
    
    public static function GetUserinfo($pid)
    {
        return Userinfo::model()->findByPk($pid);
    }
    
    public static function GetUserinfoByUsername($username)
    {
        $user = Userinfo::model() -> find("userid=:name", array(":name" => $username));
        
        if (!empty($user)) {
            return $user;
        }
        return null;
    }
    
    public static function IsExceedTraffice($pid,$size)
    {
        $traffic = CommonAdmin::GetUserTraffic($pid);
        
        if(($traffic['size']*1024*1024 + $size) >($traffic['total']*1024*1024))
        {
            return true;
        }else{
            return false;
        }
    }
    
    public static function IsExceedPicCount($pid,$size,&$pay)
    {
        $piccount = CommonAdmin::GetUserPicCount($pid);
        
        $pay = $piccount['pay'];
        
        if(($piccount['size'] + $size) >($piccount['total']))
        {
            return true;
        }else{
            return false;
        }
    }
    
    public static function GetBabyInfo($babyid)
    {
        return Babyinfo::model()->findByPk($babyid);
    }
    
    public static function GetUserPicCount($pid)
    {
        $userinfo = CommonAdmin::GetUserinfo($pid);
        
        $criteria = new CDbCriteria();
            
        $today = date("Y-m-d",time());
            
        $zone = $userinfo->zone;
        
        $usersub = CacheAdmin::GetUserSub($pid);
        
        $retDay = "";
        
        $total = 0;
        //未订购
        
        $localfirstday = '';
        $locallastday = '';
        
        $pay = 0;
        
        //var_dump($usersub);
        
        $productid = "";
        
        if($usersub == false)
        {
            $retDay = DateUtil::getTheMonth($today);
            $total = CommonAdmin::COUNT_FOR_FREE;
            
            //tranfer to utc time
            if($zone > 0)
            {
                $localfirstday = date('Y-m-d H:i:s',strtotime("$retDay[0] - $zone hour"));
                $locallastday = date('Y-m-d H:i:s',strtotime("$retDay[1] - $zone hour"));
            }else{
                $zone = -$zone;
                $localfirstday = date('Y-m-d H:i:s',strtotime("$retDay[0] + $zone hour"));
                $locallastday = date('Y-m-d H:i:s',strtotime("$retDay[1] + $zone hour"));
            }
        
        }else{
            //订购
            //$usersub = $this->GetUserBuySubID($pid);
            
            $retDay = array($usersub['createtime'],$usersub['expiretime']);
            $total = CommonAdmin::COUNT_FOR_PAY;
            
            $localfirstday = $retDay[0];
            $locallastday = gmdate('Y-m-d H:i:s',$retDay[1]);
            
            $productid = $usersub['productid'];
            
            $pay = 1;
            
        }
        
        //echo $zone;
        
        
        
        $conn = Yii::app() -> db;

        $command = $conn -> createCommand("select count(*) as size from pictures where pid= :pid and uploadservertime >= '$localfirstday' and uploadservertime <= '$locallastday'");

        $command -> bindParam(":pid", $pid, PDO::PARAM_INT);

        $dataReader = $command -> query();
        $ret = array();

        //$sysinfo = "{";
        foreach ($dataReader as $row) {
            //$returnString = $returnString.$row['variable'].':'.$row['value'];
            array_push($ret,$row);
        }
        
        if(count($ret > 0))
        {
            $ret[0]['total'] = $total;
            $ret[0]['begintime'] = $localfirstday;
            $ret[0]['endtime'] = $locallastday;
            $ret[0]['productid'] = $productid;
            $ret[0]['pay'] = $pay;
            
            return $ret[0];
        }else{

            return array("size" => 0,"total"=>$total,"begintime"=>$localfirstday,"endtime"=>$locallastday,"pay"=>$pay,"productid"=>"");
        }
    }
    
    public static function GetUserTraffic($pid)
    {
        $userinfo = CommonAdmin::GetUserinfo($pid);
        
        $value = CacheAdmin::GetUserTrafficCache($pid);
        
        if($value == false)
        {
            $criteria = new CDbCriteria();
            
            $today = date("Y-m-d",time());
            
            $zone = $userinfo->zone;
            
            //$lastday = date('Y-m-d 23:59:59', strtotime("$firstday +1 month -1 day"));
            
            $usersub = CacheAdmin::GetUserSub($pid);
            
            $retDay = "";
            
            $total = 0;
            //未订购
            if($usersub == false)
            {
                $retDay = DateUtil::getTheMonth($today);
                $total = CommonAdmin::TOTAL_FOR_FREE;
            }else{
                //订购
                //$usersub = $this->GetUserBuySubID($pid);
                
                $retDay = array($usersub['effectivetime'],$usersub['endtime']);
                $total = CommonAdmin::TOTAL_FOR_PAY;
            }
            
            //echo $zone;
            
            if($zone > 0)
            {
                $localfirstday = date('Y-m-d H:i:s',strtotime("$retDay[0] - $zone hour"));
                $locallastday = date('Y-m-d H:i:s',strtotime("$retDay[1] - $zone hour"));
            }else{
                $zone = -$zone;
                $localfirstday = date('Y-m-d H:i:s',strtotime("$retDay[0] + $zone hour"));
                $locallastday = date('Y-m-d H:i:s',strtotime("$retDay[1] + $zone hour"));
            }
            
            $conn = Yii::app() -> db;

            $command = $conn -> createCommand("select SUM(size) as size from pictures where pid= :pid and uploadservertime >= '$localfirstday' and uploadservertime <= '$locallastday'");
    
            $command -> bindParam(":pid", $pid, PDO::PARAM_INT);
    
            $dataReader = $command -> query();
            $ret = array();
    
            //$sysinfo = "{";
            foreach ($dataReader as $row) {
                //$returnString = $returnString.$row['variable'].':'.$row['value'];
                array_push($ret,$row);
            }
            
            if(count($ret > 0))
            {
                CacheAdmin::SetUserTrafficCache($pid,$ret[0]['size']);
                
                $ret[0]['total'] = $total;
                
                return $ret[0];
            }else{

                CacheAdmin::SetUserTrafficCache($pid,0);
                return array("size" => 0,"total"=>$total);
            }
        }else{
            //echo "cache";
            
            return array("size" => $value,"total"=>$total);
        }
    }

    public static function AddTrafficValue($pid,$value)
    {
        $cursize = CommonAdmin::GetUserTraffic($pid);
        
        $cursize['size'] = $cursize['size'] + $value;
        
        CacheAdmin::SetUserTrafficCache($pid,$cursize);
    }

    public static function ProcessAppleTrdata($value)
    {
        $pid = $value->pid;
        //$data = base64_encode($value->data);
        
        $data = Yii::app()->CURL->run(CommonAdmin::APPLE_AUTH_URL,FALSE,
        json_encode(array(
            'receipt-data'=>$value->data,
            'password'=>'c9e4a8d91b3d41fea1bfe2dd9fd24d87'
                    )),TRUE
            ,TRUE);

        $data = json_decode($data);
        
        //var_dump($data);
        
        $status = $data->status;
        
        $value->metadata = serialize($data);
        
        if($status == 0)
        {
            $trans = DBUtil::MasterDBBeginTransaction();
            
            $productid = $data->latest_receipt_info->product_id;
            $expire = $data->latest_receipt_info->expires_date/1000;
            
            try
            {
                if($expire > $value->expiretime)
                {
                    $value->status = 0;
                    $value->isactive = 1;
                    $value->expiretime = $expire;
                    $value->callbacktime= DateUtil::GetCurrentUTCDateTime();
                    $value->save(false);
                    
                    CacheAdmin::SetUserSubCache($pid, $value->attributes, $expire);
                }else{
                    if($value->isactive == 0)
                    {
                        $value->status = 0;
                        $value->isactive = 1;
                        $value->expiretime = $expire;
                        $value->callbacktime= DateUtil::GetCurrentUTCDateTime();
                        $value->save(false);
                        
                        CacheAdmin::SetUserSubCache($pid, $value->attributes, $expire);
                    }
                }              

                $trans->commit();
                
                return $status;
                
            }catch(exception $e)
            {
                $trans->rollback();
                
                CacheAdmin::DeleteUserSubCache($pid);
                
                return MsgConst::INVALID_VALUE;
            }
        }else{
            $value->status = $status;
            $value->isactive = 0;
            $value->callbacktime= DateUtil::GetCurrentUTCDateTime();
            $value->save(false);
            
            return $status;
        }
    }
	 public static function DisableOtherRequest($pid,$username,$target_email)
	 {
		 $requestlist = Requestinfo::model() -> findAll("pid=:pid AND userid =:userid and target_email <>:target_email and status = 0", array(":pid" => $pid, ":userid" => $username, ":target_email" => $target_email));
		 $count = count($requestlist);
		 
		 for($i=0;$i<$count;$i++)
		 {
			 $requestinfo = $requestlist[$i];
			 $requestinfo->status = -1;
			 $requestinfo->save(false);
			 
			 
			 
		 }
		 
	 }
	 
	 public static function unixtime_to_date($unixtime, $timezone)
	  {
		  date_default_timezone_set ('Asia/Shanghai');
    $time = $unixtime + $timezone * 3600;
    $datetime = new DateTime("@$time"); //DateTime类的bug，加入@可以将Unix时间戳作为参数传入DateTime构造函数
    return $datetime->format("Y-m-d H:i:s");//输出2038-01-19 11:14:07
}

	 
}
